package com.example.androidtest_download;

import cn.bvin.lib.module.downloads.DownloadManager;
import cn.bvin.lib.module.downloads.DownloadManager.Query;
import cn.bvin.lib.module.downloads.DownloadManager.Request;
import cn.bvin.lib.module.downloads.Downloads;
import cn.bvin.library.debug.SimpleLogger;
import android.app.Activity;
import android.content.ContentUris;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

	private DownloadManager dm;
	
	private long currentDownloadId;
	
	public static final String URL = "http://weixiaomi007.com/ruanjian/wxm.apk";
	
	DownloadObserver observer;
	
	private ProgressBar pb;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dm = new DownloadManager(getContentResolver(), getPackageName());
		setContentView(R.layout.activity_main);
		pb = (ProgressBar) findViewById(R.id.progressBar1);
		currentDownloadId = getPreferences(MODE_PRIVATE).getLong("currentDownloadId", -1);
		if (currentDownloadId>0) {
			Cursor cursor = query(currentDownloadId);
			if (cursor!=null&&cursor.moveToFirst()) {
				pb.setMax(cursor.getInt(cursor.getColumnIndex(Downloads.COLUMN_TOTAL_BYTES)));
				pb.setProgress(cursor.getInt(cursor.getColumnIndex(Downloads.COLUMN_CURRENT_BYTES)));
			}
			cursor.close();
		}
		if (isDownloadComplete(currentDownloadId)) {
			((Button)findViewById(R.id.button1)).setText("新建下载");
			pb.setMax(0);
			pb.setProgress(0);
		}
	}
	
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (observer!=null) {
			getContentResolver().unregisterContentObserver(observer);
		}
		
	}



	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int total = msg.arg1;
			pb.setMax(total);
			pb.setProgress(msg.what);
		}
	};
	
	public void startDownload(View v) {
		if (isDownloadComplete(currentDownloadId)||currentDownloadId<=0) {
			Uri srcUri = Uri.parse(URL);
			DownloadManager.Request request = new Request(srcUri);
			request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/");
			currentDownloadId = dm.enqueue(request);
			SimpleLogger.log_e("当前downloadId:", currentDownloadId);
			getPreferences(MODE_PRIVATE).edit().putLong("currentDownloadId", currentDownloadId).commit();
			observer = new DownloadObserver(handler, currentDownloadId);
			getContentResolver().registerContentObserver(Downloads.CONTENT_URI, true, observer);
		}else {
			dm.resumeDownload(currentDownloadId);
			observer = new DownloadObserver(handler, currentDownloadId);
			getContentResolver().registerContentObserver(Downloads.CONTENT_URI, true, observer);
		}
	}
	
	public void pauseDownload(View v) {
		dm.pauseDownload(currentDownloadId);
	}

	public void cancelDownload(View v) {
		dm.remove(currentDownloadId);
	}
	
	public void deleteDownload(View v) {
	}

	private boolean isDownloadComplete(long id) {
		boolean isComplete = false;
		DownloadManager.Query query = new Query();
		query.setFilterById(id);
		Cursor cursor = dm.query(query);
		if (cursor!=null&&cursor.moveToFirst()) {
			isComplete = DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
		}
		cursor.close();
		return isComplete;
	}
	
	public class DownloadObserver extends ContentObserver{

		long id;
		Handler handler;
		
		public DownloadObserver(Handler handler, long id) {
			super(handler);
			this.id = id;
			this.handler = handler;
		}

		@Override
		public void onChange(boolean selfChange, Uri uri) {
			Cursor cursor = query(id);
			if (cursor!=null&&cursor.moveToFirst()) {
				Message msg = handler.obtainMessage();
				msg.what = cursor.getInt(cursor.getColumnIndex(Downloads.COLUMN_CURRENT_BYTES));
				msg.arg1 = cursor.getInt(cursor.getColumnIndex(Downloads.COLUMN_TOTAL_BYTES));
				SimpleLogger.log_e("总共："+msg.arg1, "当前："+msg.what);
				handler.sendMessage(msg); 
			}
			cursor.close();
		}
		
		
	}
	
	private Cursor query(long id) {
		Uri uri = ContentUris.withAppendedId(Downloads.CONTENT_URI, id);
		return getContentResolver().query(uri, new String[]{Downloads.COLUMN_CURRENT_BYTES,
				Downloads.COLUMN_TOTAL_BYTES}, null, null, null);
	}
}
